package edu.sjsu.itack.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.sjsu.itack.entity.User;
import edu.sjsu.itack.util.ITackException;

public class UserDao {

	public void createUser(User user) throws ITackException {
		String query = "insert into user (first_name,last_name,email,password,gender) values(?,?,?,?,?);";
		Connection con = null;
		try {
			con = ConnectionFactory.getInstance().getConnection();
			PreparedStatement ps = con.prepareStatement(query);
			ps.setString(1, user.getFirstName());
			ps.setString(2, user.getLastName());
			ps.setString(3, user.getEmail());
			ps.setString(4, user.getPassword());
			ps.setString(5, user.getGender());
			ps.executeUpdate();
			
		}catch (SQLException e){
			throw new ITackException("EXC103", e);
		}
		finally{
			ConnectionFactory.getInstance().closeConnection(con);
		}
	}

	public User findUserByEmail(String email) throws ITackException{
        Connection con = null;
        User user = null;
		String query = "select id, first_name, last_name, password from user where email=?;";
		try {
			con = ConnectionFactory.getInstance().getConnection();
			
			PreparedStatement ps = con.prepareStatement(query);
			ps.setString(1, email);
			
			ResultSet rs = ps.executeQuery();
			if (!rs.isBeforeFirst()) {
				throw new ITackException("EXC100", null); //user name or password is incorrect;
			}
			rs.next();
			user = new User();
			user.setUserId(rs.getLong(1));
			user.setFirstName(rs.getString(2));
			user.setLastName(rs.getString(3));
			user.setEmail(email);
			user.setPassword(rs.getString(4));
			
		}catch (SQLException e){
			throw new ITackException("", e);
		}
		finally{
			ConnectionFactory.getInstance().closeConnection(con);
		}
		return user;
	}

}